<template>
  <div class="w-100">
    <el-table :data="tableData" style="width: 100%" :max-height="maxHeight">
      <el-table-column v-for="item in column" :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width">
        <template #default="{ row, $index }">
          <el-form status-icon inline-message :ref="`formRef${$index}destination`" :model="row"
            :validate-on-rule-change="true">
            <el-form-item :rules="item.rules" :prop="item.prop">
              <!-- <template #label>
                <p class="flex align-center">
                  <span>{{ item.label }}</span>
                <div>
                  <el-tooltip effect="dark" v-if="item.tip" :content="item.tip" placement="top">
                    <icon-info theme="outline" />
                  </el-tooltip>
                </div>
                </p>
              </template> -->
              <component style="width: 100%" v-bind="item" :is="typeComm[item.type] || ElInput" v-model="row[item.prop]"
                :fileLabel="item.propName" v-model:modelName="row[item.propName]" :placeholder="getPlaceholder(item)"
                :disabled="item.disabled || detail" @change="(event) => onChange(event, row, tableData)">
                <optionPage v-if="item.dicData" :type="item.type" :dicData="item.dicData"></optionPage>
              </component>
            </el-form-item>

          </el-form>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120" v-if="!detail && delBtn">
        <template #default="{ row, $index }">
          <el-button v-if="delBtn" link type="danger" size="small" @click.prevent="deleteRow(row, $index)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button class="w-100 mt10" size="small" plain @click="handleAdd" v-if="!detail && addBtn"> 添加 </el-button>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from "vue";
import { ElInput, ElMessage } from 'element-plus'
import { getComponentCollecte } from '../../hooks/index'
import optionPage from './option.vue'
const context = getCurrentInstance();

const typeComm: Object = getComponentCollecte()

type Props = {
  modelValue?: any
  column?: any
  data?: any
  detail?: boolean
  maxHeight?: string | number
  multiple?: boolean
  rowChange?: Function
  addBtn?:boolean
  delBtn?:boolean
}
const props = withDefaults(defineProps<Props>(), {
  detail: false,
  multiple: true,
  maxHeight: '380',
  column: [],
  addBtn:true,
  delBtn:true
})

const emit = defineEmits(['update:modelValue', 'add', 'remove'])
let tableData = ref([])
watch(
  () => props.modelValue,
  (val) => {
    tableData.value = val || []
  },
  {
    immediate: true,
  }
)
const getPlaceholder = (item)=> {
  if(item.placeholder) {
    return item.placeholder
  }else if(['remoteSelect','select','date','AplidAreaSelect'].includes(item.type)) {
    return `请选择${item.label}`
  }else {
    return `请输入${item.label}`
  }
}

const update = () => {
  emit('update:modelValue', tableData.value)
}
const onChange = (e, row,data) => {
  tableValidate().then(res => {
    props.rowChange && props.rowChange(e, row, data)
    update()
  }).catch(err => {
    ElMessage.warning('请检查填写内容！')
  })
}
const deleteRow = (row, index) => {
  if (props.multiple) {
    tableData.value.splice(index, 1)
    update()
  } else {
    emit('remove', row, (res) => {
      tableData.value.splice(index, 1)
    })
    update()
  }
}
const handleAdd = () => {
  tableValidate().then(res => {
    // 提取默认值
    const tempRow = {}
    props.column.forEach(item => {
     if(item.defaultValue ||item.defaultValue===0) tempRow[item.prop] = item.defaultValue
    })
    if (props.multiple || tableData.value.length == 0) {
      tableData.value.push({
        ...props.data,
        ...tempRow,
      })
      update()
    } else {
      emit('add', tableData.value, (res) => {
        tableData.value.push({
          ...props.data,
          ...tempRow
        })
      })
      update()
    }
  }).catch(err => {
    ElMessage.warning('请检查填写内容！')
  })

}

const getRuleList = () => {
  const { refs } = context;
  const resultArr: Promise<any>[] = []//用来接受返回结果的数组
  for (let key in refs) {
    if (key.substring(0, 7) == 'formRef') {
      const ruleList: any = refs[key]
      ruleList.map(itemEl => {
        const task = new Promise((resolve, reject) => {
          itemEl!.validate((valid, fields) => {
            if (valid) {
              resolve(valid)
            } else {
              reject(fields)
            }
          })
        })
        resultArr.push(task)
      })
    }
  }
  return resultArr
}
const tableValidate = () => {
  return new Promise((resolve, reject) => {
    const resultArr = getRuleList()
    Promise.all([...resultArr]).then(() => {
      resolve('ok')
    }).catch(err => {
      reject('校验失败')
    })
  })
}

defineExpose({
  tableValidate
})
</script>

<style scoped></style>
